﻿using AiBLSmartEdu.Module.SmartPhysics.API.Configurations;
using FrameworkCore.DI;
using Microsoft.Extensions.Options;
using System.Xml;

namespace AiBLSmartEdu.Module.SmartPhysics.API;

#nullable disable

/// <summary>
/// 物理问答助手
/// </summary>
public class PhysicsHelpers : IScopedDependency
{
    private readonly IOptions<SmartPhysicsSettings> _optSmartPhysicsSettings;
    private readonly HttpClient _httpClient;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="optSmartPhysicsSettings">配置</param>
    /// <param name="httpClient">HTTP请求</param>
    public PhysicsHelpers(IOptions<SmartPhysicsSettings> optSmartPhysicsSettings, HttpClient httpClient)
    {
        _optSmartPhysicsSettings = optSmartPhysicsSettings;
        _httpClient = httpClient;
    }

    /// <summary>
    /// 获取问题答案
    /// </summary>
    /// <param name="question">问题</param>
    /// <returns></returns>
    public async Task<string> FetchAnswerAsync(string question)
    {
        _httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
        _httpClient.DefaultRequestHeaders.Add("Accept", "application/json");

        try
        {
            string url = string.Format(_optSmartPhysicsSettings.Value.Url, Uri.EscapeDataString(question));

            HttpResponseMessage response = await _httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();

            string answer = await response.Content.ReadAsStringAsync();
            return answer;
        }
        catch (HttpRequestException e)
        {
            return e.Message;
        }
    }

    /// <summary>
    /// 将Xml格式内容格式转为Html内容格式
    /// </summary>
    /// <param name="xmlContent">将要转换的内容</param>
    /// <param name="title">标题</param>
    /// <returns></returns>
    public async Task<string> ConvertXmlToHtmlAsync(string xmlContent, string title)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlContent);

        // 检查查询结果的成功与否
        var queryResult = xmlDoc.SelectSingleNode("//queryresult");
        bool success = queryResult?.Attributes["success"]?.Value == "true";

        // 添加基本的 HTML 结构和样式
        string html = $@"
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; margin: 20px; }}
h1 {{ color: #2c3e50; }}
h2 {{ color: #34495e; border-bottom: 1px solid #bdc3c7; }}
p {{ font-size: 16px; line-height: 1.5; }}
img {{ max-width: 100%; height: auto; }}
.pod {{ margin-bottom: 20px; padding: 10px; border: 1px solid #ecf0f1; border-radius: 5px; }}
</style>
</head>
<body>
";

        if (!success)
        {
            html += "<h1>查询失败</h1>";
            html += "<p>抱歉，无法获取相关信息。请检查输入内容或稍后再试。</p>";

            // 可选：显示替代建议
            var didYouMeans = queryResult.SelectSingleNode("didyoumeans");
            if (didYouMeans != null)
            {
                html += "<h2>您可能想要查询：</h2><ul>";
                foreach (XmlNode didYouMean in didYouMeans.SelectNodes("didyoumean"))
                {
                    html += $"<li>{didYouMean.InnerText}</li>";
                }
                html += "</ul>";
            }
        }
        else
        {
            foreach (XmlNode pod in xmlDoc.SelectNodes("//pod"))
            {
                if (pod.Attributes["title"] != null)
                {
                    html += $@"<div class='pod'>
                        <h2>{pod.Attributes["title"].Value}</h2>";

                    foreach (XmlNode subpod in pod.SelectNodes("subpod"))
                    {
                        if (subpod.SelectSingleNode("plaintext") != null)
                        {
                            html += $@"<p>{subpod.SelectSingleNode("plaintext").InnerText}</p>";
                        }

                        var imgNode = subpod.SelectSingleNode("img");
                        if (imgNode != null && imgNode.Attributes["src"] != null)
                        {
                            string imgUrl = imgNode.Attributes["src"].Value;
                            html += $@"<img src=""{imgUrl}"" alt=""{pod.Attributes["title"].Value} 图像"" />";
                        }
                    }
                    html += "</div>";
                }
            }
        }

        html += "</body>";
        html += "</html>";

        return await Task.FromResult(html);
    }
}
